package it.win4buy.controllers
{
    import flash.events.Event;
    import flash.events.IEventDispatcher;

    import it.win4buy.entities.PlaceHolderVO;
    import it.win4buy.entities.UserDataVO;
    import it.win4buy.events.DeRegistrationPlaceHolderEvent;
    import it.win4buy.events.GetPlaceHolderEvent;
    import it.win4buy.events.GetStartuPlaceHolderListEvent;
    import it.win4buy.events.NavigationEvent;
    import it.win4buy.events.PlaceHolderEvent;
    import it.win4buy.events.RegistrationPlaceHolderEvent;
    import it.win4buy.events.UtilityEvent;
    import it.win4buy.models.ApplicationModel;
    import it.win4buy.presentations.AlertComponentPM;
    import it.win4buy.presentations.PlaceHolderViewPM;
    import it.win4buy.services.DeRegistrationPlaceHolderService;
    import it.win4buy.services.RegistrationPlaceHolderService;
    import it.win4buy.utility.LoggerUtilty;

    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.managers.CursorManager;
    import mx.managers.PopUpManager;

    /**
     *
     *	autore:
     *  pierangelo.mancusi@gmail.com
     *
     */

    public class PlaceHolderController
    {



        //-------------------------------------------
        //
        // Injected properties
        //
        //-------------------------------------------

        [Dispatcher]
        public var dispatcher:IEventDispatcher;

        [Inject]
        public var applicationModel:ApplicationModel;

        [Inject]
        public var placeHolderPM:PlaceHolderViewPM;

        [Inject]
        public var alertComponentPM:AlertComponentPM;

        [Inject]
        public var pollingController:PollingController;

        [Inject]
        public var log:LoggerUtilty;

        [Inject]
        public var registrationPlaceHolderService:RegistrationPlaceHolderService;

        [Inject]
        public var deRegistrationPlaceHolderService:DeRegistrationPlaceHolderService;

        //-------------------------------------------
        //
        // Constructor
        //
        //-------------------------------------------

        public function PlaceHolderController()
        {
        }

        //-------------------------------------------
        //
        // Mediator Handlers
        //
        //-------------------------------------------


        [EventHandler(event="PlaceHolderEvent.SET_SELECTED_INDEX", priority="990")]
        public function saveSelectedPlaceHolder(event:PlaceHolderEvent):void
        {

            applicationModel.selectedPlaceHolder=event.obj as int;

            log.logToConsole(this, "saveSelectedPlaceHolder(): [ PlaceHolder:" + applicationModel.selectedPlaceHolder + " ]");

        }



        [EventHandler(event="PlaceHolderEvent.TRY_REGISTER_USER", priority="990")]
        /**
         *
         * User Registration to the selected PLaceholder
         *
         */
        public function tryRegister(event:PlaceHolderEvent):void
        {


            if (applicationModel.selectedPlaceHolder > -1)
            {
                var t:PlaceHolderVO=(applicationModel.placeHolderList.getItemAt(applicationModel.selectedPlaceHolder) as PlaceHolderVO);

                CursorManager.getInstance().setBusyCursor();

                //invoking service
                registrationPlaceHolderService.execute(applicationModel.userData.userId, t.tableId);

            }
            else
            {
                //fixme:
                //attualmente non usato in quanto ilpulsante iscriviti si disabilita
                /*
                dispatcher.dispatchEvent(new NavigationEvent(NavigationEvent.VIEW_PLACEHOLDER_ALERT, null, true));
                alertComponentPM.btCancelVisible=false;
                alertComponentPM.message="Seleziona prima un Tavolo.";
                alertComponentPM.title="Info.";
                */
            }



        }


        [EventHandler(event="PlaceHolderEvent.TRY_UNREGISTER_USER", priority="990")]
        /**
         *
         * User UnRegistrer from to the selected Placeholder.
         *
         */
        public function tryUnRegister(event:PlaceHolderEvent):void
        {

            var t:PlaceHolderVO=(applicationModel.placeHolderList.getItemAt(applicationModel.selectedPlaceHolder) as PlaceHolderVO);
            CursorManager.getInstance().setBusyCursor();

            //invoking service
            deRegistrationPlaceHolderService.execute(applicationModel.userData.userId, applicationModel.registeredPlaceholder.toString());

        }




        [EventHandler(event="RegistrationPlaceHolderEvent.RESULT", priority="990")]
        [EventHandler(event="RegistrationPlaceHolderEvent.FAULT", priority="990")]
        public function serviceResult(event:RegistrationPlaceHolderEvent):void
        {
            switch (event.type)
            {
                case RegistrationPlaceHolderEvent.RESULT:

                    /*
                    0 Registrazione OK
                    1 Tavolo gia' in gioco
                    2 Iscrizione ai tavoli completa (nessun posto disponibile)
                    3 Credito insufficiente
                    */

                    CursorManager.getInstance().removeBusyCursor();
                    if ((event.obj as int) == 0)
                    {

                        //Registrazione OK
                        //rende visibile il btDeregister
                        dispatcher.dispatchEvent(new UtilityEvent(UtilityEvent.CHANGE_BUTTON_REGISTRATION, false, true));


                        var t:PlaceHolderVO=(applicationModel.placeHolderList.getItemAt(applicationModel.selectedPlaceHolder) as PlaceHolderVO);
                        t.playersNum=(int(t.playersNum) + 1).toString();
                        applicationModel.registeredPlaceholder=int(t.tableId);

                        //fixme:
                        //aggiona crediti

                        if (t.buyIn == "0")
                        {
                            applicationModel.userData.freeCredits=(int(applicationModel.userData.freeCredits) - int(t.freeCredits)).toString();

                        }
                        else
                        {
                            applicationModel.userData.credits=(int(applicationModel.userData.credits) - int(t.buyIn)).toString();

                        }


                        // alert registration OK
                        alertComponentPM.btConfirmVisible=true;
                        alertComponentPM.btCancelVisible=false;
                        alertComponentPM.message="Registrazione al tavolo " + "\n" + "avvuenuta con successo.";
                        alertComponentPM.title="Info";

                        dispatcher.dispatchEvent(new NavigationEvent(NavigationEvent.VIEW_PLACEHOLDER_ALERT, null, true));

                    }
                    else
                    {
                        dispatcher.dispatchEvent(new NavigationEvent(NavigationEvent.VIEW_PLACEHOLDER_ALERT, null, true));

                        if ((event.obj as int) == 1)
                        {
                            alertComponentPM.btConfirmVisible=true;
                            alertComponentPM.btCancelVisible=false;
                            alertComponentPM.message="Partita già iniziata.";
                            alertComponentPM.title="Attenzione.";


                        }
                        else
                        {
                            if ((event.obj as int) == 2)
                            {
                                alertComponentPM.btConfirmVisible=true;
                                alertComponentPM.btCancelVisible=false;
                                alertComponentPM.message="Tavolo pieno.";
                                alertComponentPM.title="Attenzione.";
                            }
                            else
                            {
                                if ((event.obj as int) == 3)
                                {
                                    alertComponentPM.btConfirmVisible=true;
                                    alertComponentPM.btCancelVisible=false;
                                    alertComponentPM.message="Credito insufficiente.";
                                    alertComponentPM.title="Attenzione";
                                }
                            }

                        }

                    }


                    //fixme: 
                    //se il tavolo e' completo vai al Application.MODE=PLAY
                    //per ora non lo mando mai
                    if (false)
                    {
                        //update Datagrid
                        refreshDataBinding();

                        dispatcher.dispatchEvent(new NavigationEvent(NavigationEvent.VIEW_AC_PLAY, null, true));
                    }
                    else
                    {

                        //update Datagrid
                        refreshDataBinding();

                    }



                    break;

                case RegistrationPlaceHolderEvent.FAULT:

                    CursorManager.getInstance().removeBusyCursor();
                    //show message error
                    //fixme:labels
                    dispatcher.dispatchEvent(new NavigationEvent(NavigationEvent.VIEW_PLACEHOLDER_ALERT, null, true));
                    alertComponentPM.btCancelVisible=false;
                    alertComponentPM.message="Attenzione:" + "\n" + "Registrazione non avvenuta." + "\n" + event.obj.toString();
                    alertComponentPM.title="Info";
                    break;


            }

        }


        [EventHandler(event="DeRegistrationPlaceHolderEvent.RESULT", priority="990")]
        [EventHandler(event="DeRegistrationPlaceHolderEvent.FAULT", priority="990")]
        public function serviceDeregistrationResult(event:DeRegistrationPlaceHolderEvent):void
        {

            switch (event.type)
            {
                case DeRegistrationPlaceHolderEvent.RESULT:
                    CursorManager.getInstance().removeBusyCursor();
                    log.logToConsole(this, "[serviceDeregistrationResult()] Deregistration OK.");

                    var t:PlaceHolderVO=null;
                    for (var i:int=0; i < applicationModel.placeHolderList.length - 1; i++)
                    {
                        var t2:PlaceHolderVO=(applicationModel.placeHolderList.getItemAt(i) as PlaceHolderVO);


                        if (int(t2.tableId) == applicationModel.registeredPlaceholder)
                        {

                            t=t2;
                        }


                    }

                    t.playersNum=(int(t.playersNum) - 1).toString();


                    //aggiona crediti

                    if (t.buyIn == "0")
                    {
                        applicationModel.userData.freeCredits=(int(applicationModel.userData.freeCredits) + int(t.freeCredits)).toString();

                    }
                    else
                    {
                        applicationModel.userData.credits=(int(applicationModel.userData.credits) + int(t.buyIn)).toString();

                    }


                    //rende invisibile il btDeregister
                    dispatcher.dispatchEvent(new UtilityEvent(UtilityEvent.CHANGE_BUTTON_REGISTRATION, true, true));
                    refreshDataBinding();




                    // alert registration OK
                    alertComponentPM.btConfirmVisible=true;
                    alertComponentPM.btCancelVisible=false;
                    alertComponentPM.message="Deregistrazione al tavolo " + "\n" + "avvenuta con successo.";
                    alertComponentPM.title="Info";

                    dispatcher.dispatchEvent(new NavigationEvent(NavigationEvent.VIEW_PLACEHOLDER_ALERT, null, true));

                    applicationModel.registeredPlaceholder=-1;
                    t2=null;
                    t=null;

                    break;


                case DeRegistrationPlaceHolderEvent.FAULT:
                    CursorManager.getInstance().removeBusyCursor();
                    log.logToConsole(this, "Deregistration OK.");

                    break;


            }

        }


        //-------------------------------------------
        //
        // Private Methods
        //
        //-------------------------------------------

        /**
         * Force Refreshing DataBinding in the application
         *
         */
        private function refreshDataBinding():void
        {

            dispatcher.dispatchEvent(new UtilityEvent(UtilityEvent.REFRESH_BINDING, null, true));

        }


        private function clickOK(event:Event):void
        {

            CursorManager.getInstance().removeBusyCursor();
        }
    }
}